﻿
using System.Windows;
using System.Windows.Input;

namespace Wpf2.ViewModels
{
    public class PropertyControls
    {
        private static DependencyProperty _property;
        private static readonly RoutedEvent SelectionChangedEvent = UIElement.KeyDownEvent;

        public static readonly DependencyProperty SelectionChangedCommandProperty =
            DependencyProperty.RegisterAttached("LoadCommand",
            typeof(ICommand), typeof(PropertyControls),
            new PropertyMetadata(SelectionChangedCallBack));

        public static void SetSelectionChangedCommand(UIElement obj, ICommand value)
        {
            obj.SetValue(SelectionChangedCommandProperty, value);
        }

        public static ICommand GetSelectionChangedCommand(UIElement obj)
        {
            return (ICommand)obj.GetValue(SelectionChangedCommandProperty);
        }

        static void SelectionChangedCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var element = obj as UIElement;

            _property = args.Property;

            if (element == null) return;
            if (args.OldValue != null)
            {
                element.AddHandler(SelectionChangedEvent, new RoutedEventHandler(EventHandler));
            }

            if (args.NewValue != null)
            {
                element.AddHandler(SelectionChangedEvent, new RoutedEventHandler(EventHandler));
            }
        }

        public static void EventHandler(object sender, RoutedEventArgs e)
        {
            var obj = sender as DependencyObject;

            if (obj == null) return;
            var command = obj.GetValue(_property) as ICommand;

            if (command == null) return;
            if (command.CanExecute(e))
            {
                /*var lb = e.OriginalSource as ListBox;

                if (lb != null)
                {
                    command.Execute(lb.SelectedItem);
                }*/
            }
        }
    }
}
